<template>
  <main id="home" class="view" role="main">
    <div class="md-example-child md-example-child-picker md-example-child-picker-2">
      <p style="font-size: 14px; background-color: #2b68e9;color: #fbf8f8;height:25px;text-align: center;padding-top: 5px;">这里是惠州。入网信息（根据国家实名制要求，请准确提供身份证信息）</p>
      <md-field>
        <md-input-item  ref="input0" title="姓名" v-model="cert_name"  clearable placeholder="请输入姓名" :maxlength="50">
          <icon style="color: red" name="bank-name" slot="left">*</icon>
        </md-input-item>

        <md-input-item  ref="input0" title="身份证号码" v-model="cert_no"  clearable placeholder="请输入身份证号码" :maxlength="50">
          <icon style="color: red" name="bank-card" slot="left">*</icon>
        </md-input-item>
        <md-input-item  ref="input1" title="联系电话" v-model="cert_num" clearable placeholder="请输入联系电话"  :maxlength="20" >
          <icon style="color: red" name="bank-mobile" slot="left">*</icon>
        </md-input-item>
      </md-field>
      <md-picker ref="picker2" v-model="isPickerShow2"
                 :data="pickerData3" :cols="2" is-cascade large-radius title="选择归属地省市" @change="onPickerConfirm2"  @confirm="onPickerConfirm2" ></md-picker>
      <md-field>
        <md-input-item  ref="input12" title="归属地" placeholder="请选择归属地"   @focus="isPickerShow2 = true" readonly v-model="picker2Value" >
          <icon style="color: red" name="bank-belong-area" slot="left">*</icon>
          <icon name="info" slot="right" style="font-size: 12px;width:40px;height:40px;" @click="isPickerShow2 = true">点击获取</icon>
        </md-input-item>
      </md-field>
      <md-field>
        <md-input-item  title="选择号码" v-model="select_mobile_number" @focus="showPopUp('bottom')"  placeholder="双击请选择号码"  readonly >
          <icon style="color: red" name="bank-mobile-select" slot="left" >*</icon>
          <icon name="info" slot="right" style="font-size: 12px;width:40px;height:40px;" @click="showPopUp('bottom')">点击获取</icon>
        </md-input-item>
      </md-field>
      <md-field>
        <md-field-item title="省市区/县" arrow="arrow"  :value="pickerValue1"  @click="isPickerShow1 = true">
        </md-field-item>
      </md-field>
      <md-field>
        <md-input-item  ref="input12" title="请输入地址" placeholder="详细地址"   v-model="address" >
          <icon style="color: red" name="bank-belong-area2" slot="left">*</icon></md-input-item>
      </md-field>
      <md-picker  ref="picker1" @change="onPickerConfirm" v-model="isPickerShow1" :data="pickerData3" :cols="3" is-cascade large-radius title="选择省市区/县"
                  :default-index="pickerDefaultIndex"  @confirm="onPickerConfirm"
                  :default-value="pickerDefaultValue"    @initialed="onPickerInitialed" ></md-picker>
      <p slot="footer" style="height:50px;"></p>
      <md-agree v-model="agreeConf.checked" :disabled="agreeConf.disabled" :size="agreeConf.size" font-size="12px"
                @change="onChange(agreeConf.name, agreeConf.checked, $event)" >我已阅读并同意《客户入网服务协议及业务协议》
      </md-agree>
      <div style="font-size: 14px;float:left;margin: 15px 10px 0px 10px; "> 1、未满16周岁的，因政策原因不发货，请勿下单。</div>
      <div style="font-size: 14px;float:left;margin: 5px 10px; "> 2、请保持电话畅通，我们将随时可能与您联系。 </div>
      <md-button type="primary" @click="createOrder" v-if="agree_yes">
        <span>确认保存</span>
      </md-button>
      <md-button type="primary" disabled @click="createOrder" v-if="agree_no">
        <span>确认保存</span>
      </md-button>
    </div>
    <md-popup v-model="isPopupShow.bottom" position="bottom" >
      <md-popup-title-bar
        title="号码选择"
        cancel-text="取消"
        large-radius
        @confirm="hidePopUp('bottom')"
        @cancel="hidePopUp('bottom')"
      ></md-popup-title-bar>
      <div class="md-example-popup md-example-popup-bottom">
        <div class="choose_left_1" >
          <div class="choose_center_1" v-for="(item,index) in allMobileListToShow[0]"  @click="choose_number(item,index)"  >{{item}}</div>
        </div>
        <div class="choose_right_1">
          <div class="choose_center_1" v-for="(item,index) in allMobileListToShow[1]"  @click="choose_number(item, index)" >{{item}}</div>
        </div>
        <div class="choose_next_1">
          <md-button type="warning" size="small" style="font-size: 18px;margin-top: 10px;padding: 20px;" inline>换一批</md-button>
        </div>
      </div>
    </md-popup>
  </main>

</template>

<script>
import { Popup, Button, InputItem, Toast, ActivityIndicator, Dialog, DropMenu, PopupTitleBar, CheckBox, Picker, Field, FieldItem, Agree, NoticeBar, Icon } from 'mand-mobile'
import district from 'mand-mobile/components/picker/demo/data/district'
import axios from 'axios'

export default {
  name: 'huizhou-view',
  components: {
    [CheckBox.name]: CheckBox,
    [Popup.name]: Popup,
    [NoticeBar.name]: NoticeBar,
    [InputItem.name]: InputItem,
    [Button.name]: Button,
    [ActivityIndicator.name]: ActivityIndicator,
    [DropMenu.name]: DropMenu,
    [Picker.name]: Picker,
    [Field.name]: Field,
    [FieldItem.name]: FieldItem,
    [Agree.name]: Agree,
    [Icon.name]: Icon,
    [PopupTitleBar.name]: PopupTitleBar
  },
  data () {
    return {
      cert_name: '', // 姓名
      cert_no: '', // 身份证号码
      cert_num: '', // 自己电话，非购买的
      loading: false,
      isPickerShow1: false,
      isPickerShow2: false,
      pickerData1: district,
      pickerData2: [],
      pickerData3: [],
      pickerValue1: '',
      provinceList: [],
      agreeConf: {
        checked: false,
        name: 'agree0',
        size: 'md',
        disabled: false,
        introduction: '选中状态'
      },
      open: false,
      url: {
        list: '/agentgetcity',
        agentgetprotocol: '/agentgetprotocol',
        getMobilelist: '/agentselectnumber',
        saveOrder: '/agentorderadd',
        orderNotice: '/agentordernotice',
        agentgetcustinfo: '/agentgetcustinfo',
        gettoken: '/gettoken'
      },
      callback_url: '',
      agree_yes: false,
      agree_no: true,
      pickerData: [],
      pickerDefaultIndex: [],
      pickerDefaultValue: [],
      agentgetprotocolText: '', // 协议文本说明
      provinceValue: '',
      province2Value: '',
      cityValue: '',
      city2Value: '',
      pickerValue: '',
      picker2Value: '',
      areaValue: '',
      address: '', // 详细地址
      user_check_protocol: false,
      jsonData: [{'a': 1}],
      isPopupShow: {},
      select_mobile_number: '', // 选择的电话号码
      allMobileListToShow: [['13322222220', '13322222221', '13322222222', '13322222223', '13322222224'], ['13322222225', '13322222226', '13322222227', '13322222228', '13322222229']] // 初始化供选择的电话号码列表
    }
  },
  methods: {
    showPopUp (type) {
      if (this.province2Value === '' || this.city2Value === '') {
        Toast.info('请先选择手机号码归属地')
      } else {
        this.getRemoteMobile()
        this.$set(this.isPopupShow, type, true)
      }
    },
    hidePopUp (type) {
      this.$set(this.isPopupShow, type, false)
    },
    onChange (name, checked) {
      if (checked) {
        this.user_check_protocol = true
        this.agree_yes = true
        this.agree_no = false
      } else {
        this.agree_yes = false
        this.agree_no = true
        this.user_check_protocol = false
      }
      console.log(`agree name = ${name} is ${checked ? 'checked' : 'unchecked'}`)
    },
    choose_number (number, index) {
      console.log(number)
      this.hidePopUp('bottom')
      this.select_mobile_number = number
    },
    onClick () {
      Dialog.alert({
        content: '点击了'
      })
    },
    createOrder () {
      if (this.cert_name === '') {
        Toast.info('请输入姓名')
        return
      }
      if (this.cert_no === '') {
        Toast.info('请输入身份证号码')
        return
      }
      if (this.cert_no.length > 0) {
        if (!this.validateIdCard(this.cert_no)) {
          Toast.info('请输入正确的十八位身份证号码')
          return
        }
      }
      if (this.cert_num === '') {
        Toast.info('请输入手机号码')
        return
      }
      if (this.cert_num.length > 11 || this.cert_num.length < 11) {
        Toast.info('请输入正确的手机号码')
        return
      }
      if (this.province2Value === '' || this.city2Value === '') {
        Toast.info('请选择归属地')
        return
      }
      if (this.select_mobile_number === '') {
        Toast.info('请选择手机号码')
        return
      }
      if (this.provinceValue === '' || this.cityValue === '') {
        Toast.info('请选择邮寄地址')
        return
      }
      this.saveOrder()
    },
    onPickerInitialed () {
      const columnValues = this.$refs.picker1.getColumnValues()
      let value = ''
      columnValues.forEach(item => {
        value += `${item.label}-`
      })
      console.log(`getColumnValues: ${value.substr(0, value.length - 1)}`)
    },
    getColumnIndex (picker, index) {
      console.log(index)
      const value = this.$refs.picker1.getColumnIndex(index)
      Dialog.alert({
        content: `<pre>${JSON.stringify(value)}</pre>`
      })
    },
    getCityByProvince (code) {
      let tmp2 = []
      axios.post(this.url.list, { 'code': code }).then((r) => {
        let cityTmp = r.data.data.con
        cityTmp.forEach(item => {
          let tmp = {
            'value': item.code,
            'label': item.name,
            'children': [{
              'value': '1',
              'label': '请选择'}]
          }
          tmp2.push(tmp)
        })

        let waitTmp = this.pickerData3[0]
        for (let i = 0; i < waitTmp.length; i++) {
          if (waitTmp[i].value === code) {
            waitTmp[i] = {
              'value': waitTmp[i].value,
              'label': waitTmp[i].label,
              'children': tmp2
            }
          }
        }
        this.pickerData3[0] = waitTmp

        cityTmp.forEach(item => {
          this.getAreaByCity(code, item.code)
        })
        // console.log(1)
      })
    },

    getAreaByCity (provinceValue, cityValue) {
      // console.log('getArea2ByCity provinceValue : ' + provinceValue)
      // console.log('getArea2ByCity cityValue : ' + cityValue)
      let tmp22 = []
      axios.post(this.url.list, {'code': cityValue}).then((r) => {
        if (r.data.data) {
          let areaTmp = r.data.data.con
          areaTmp.forEach(item => {
            let tmp = {
              'value': item.code,
              'label': item.name
            }
            tmp22.push(tmp)
          })
          let waitTmp2 = this.pickerData3[0]
          for (let i = 0; i < waitTmp2.length; i++) {
            if (waitTmp2[i].value === provinceValue) {
              for (let ii = 0; ii < waitTmp2[i].children.length; ii++) {
                if (waitTmp2[i].children[ii].value === cityValue) {
                  waitTmp2[i].children[ii] = {
                    'value': waitTmp2[i].children[ii].value,
                    'label': waitTmp2[i].children[ii].label,
                    'children': tmp22
                  }
                }
              }
            }
          }
          this.pickerData3[0] = waitTmp2
        }
      })
    },
    getProvinceCity () {
      let param = {}
      axios.post(this.url.list, param).then((r) => {
        this.provinceList = r.data.data.con
        this.provinceList.forEach(item => {
          let tmp = {}
          // 初始化区县列表
          tmp = {
            'value': item.code,
            'label': item.name,
            'children': [{
              'value': '0',
              'label': '请选择省'}]
          }
          this.pickerData2.push(tmp)
        })
        this.pickerData3.push(this.pickerData2)
        this.provinceList.forEach(item => {
          // 初始化市的列表，第一次点击的时候有点问题，不显示第二 第三
          if (item.code !== '11000000') {
            this.getCityByProvince(item.code)
          }
        })
      }).finally(() => {

      })
    },
    handleClick () {
      Toast.info('点击按钮2')
    },
    // 选择邮寄省市区的地址
    onPickerConfirm (columnIndex, itemIndex, value) {
      if (columnIndex === 2) {
        this.areaValue = value.value
        // console.log('areaValue: ' + this.areaValue)
      }
      if (columnIndex === 1) {
        this.cityValue = value.value
        this.getAreaByCity(this.provinceValue, this.cityValue)
      }
      const values = this.$refs[`picker1`].getColumnValues()
      if (columnIndex === 0) {
        this.provinceValue = value.value
        this.getCityByProvince(values[0].value)
      }
      let res = ''
      values.forEach(value => {
        value && (res += `${value.text || value.label} `)
      })
      console.log(values[0].label + '- ' + values[0].value + '- ' + values[1].label + '- ' + values[1].value + '- ' + values[2].label + '- ' + values[2].value)
      this.pickerValue1 = res
      if (this.provinceValue === '') {
        this.provinceValue = values[0].value
      }
      if (this.cityValue === '') {
        this.cityValue = values[1].value
      }
      if (this.areaValue === '') {
        this.areaValue = values[2].value
      }
    },
    // 选择归属地
    onPickerConfirm2 (columnIndex, itemIndex, value) {
      console.log(columnIndex)
      const values = this.$refs[`picker2`].getColumnValues()
      if (columnIndex === 0) {
        this.province2Value = value.value
        console.log('provinceValue: ' + this.province2Value)
        this.getCityByProvince(values[0].value)
      }
      if (columnIndex === 1) {
        this.city2Value = value.value
        console.log('cityValue: ' + this.city2Value)
      }
      if (this.province2Value == '') {
        this.province2Value = values[0].value
      }
      if (this.city2Value == '') {
        this.city2Value = values[1].value
      }
      this.picker2Value = values[0].label + ' - ' + values[1].label
      console.log(values[0].label + '- ' + values[0].value + '- ' + values[1].label + '- ' + values[1].value)
    },
    // 获取商家的登录凭证Token。
    gettoken () {
      let param = {
        'app_id': 'appid1',
        'app_secret': 'appsecret1'
      }
      axios.post(this.url.gettoken, param).then((r) => {
        if (r.data.data) {
          console.log(r.data.data)
        }
      })
    },
    // 获取系统公告信息，是运营商的相关规定与说明。
    agentgetcustinfo () {
      let param = {}
      axios.post(this.url.agentgetcustinfo, param).then((r) => {
        if (r.data.data) {
          console.log(r.data.data)
        }
      })
    },
    getRemoteMobile () {
      let param = {
        'province_code': this.province2Value,
        'city_code': this.city2Value,
        'goods_id': '981610241535',
        'search_value': '',
        'amounts': 10
      }
      axios.post(this.url.getMobilelist, param).then((r) => {
        if (r.data.data) {
          console.log(r.data.data)
        }
        this.allMobileListToShow[0] = ['13322222220', '13322222221', '13322222222', '13322222223', '13322222224']
        this.allMobileListToShow[1] = ['13322222225', '13322222226', '13322222227', '13322222228', '13322222229']
      })
    },
    // 回调
    //   ● 1 已下单待支付
    //   ● 2 已付款待发货
    //   ● 3 已从总部发货待收货
    //   ● 4 已发货到自提点待收货
    //   ● 5 已收货签收待评价
    //   ● 6 已收货签收需要退货
    //   ● 7 已退货
    //   ● 8 已理赔
    //   ● 9 已经取消
    //   ● 10 已经完成
    orderNotice () {
      let param = {
        'type': 1
      }
      axios.post(this.url.orderNotice, param).then((r) => {
        if (r.data.data) {
          console.log(r.data.data)
        }
      })
    },
    saveOrder () {
      let param = {
        'cert_name': this.cert_name,
        'cert_num': this.select_mobile_number,
        'cert_no': this.cert_no,
        'contact_num': this.cert_num,
        'post_province_code': this.provinceValue,
        'post_city_code': this.cityValue,
        'post_district_code': this.areaValue,
        'post_addr': this.address,
        'province_code': this.province2Value,
        'city_code': this.city2Value,
        'callback_url': this.callback_url
      }
      axios.post(this.url.saveOrder, param).then((r) => {
        if (r.data.code === 0) {
          console.log(r.data.data)
          Toast.info('下单成功')
          this.cert_name = ''
          this.cert_no = ''
          this.cert_num = ''
          this.select_mobile_number = ''
        } else {
          Toast.info('下单失败')
        }
      })
    },
    getNetProtocol () {
      let param = {'type': 1}
      axios.post(this.url.agentgetprotocol, param).then((r) => {
        this.agentgetprotocolText = r.data.data.con
      }).finally(() => {

      })
    },
    validateIdCard (idCardNumber) {
      // 身份证号码正则表达式
      const idCardRegex = /^[1-9]\d{5}(19|20)(\d{2})(0[1-9]|1[0-2])(0[1-9]|[1-2]\d|3[0-1])\d{3}(\d|X|x)$/
      if (idCardNumber && !idCardRegex.test(idCardNumber)) {
        return false
      } else {
        return true
      }
    },
    download (waitTmp) {
      // var jsonDataStr = JSON.stringify(waitTmp)
      // // 创建一个Blob对象
      // var blob = new Blob([jsonDataStr], {type: 'text/plain;charset=utf-8'})
      // // 创建一个URL对象
      // var url = window.URL.createObjectURL(blob)
      // // 创建一个a标签
      // var a = document.createElement('a')
      // a.href = url
      // a.download = 'data.json'
      // // 模拟用户点击下载链接
      // var evt = document.createEvent('MouseEvents')
      // evt.initEvent('click', true, true)
      // a.dispatchEvent(evt)
    }
  },
  mounted () {
    this.getProvinceCity()
    this.getNetProtocol()
    this.pickerDefaultIndex = [0, 0, 0]
    // https://apijob.bld365.com/api/jx/sale/order/callback?productCode=SPC2023103015014000000001&bizType=10&channelCode=JX&sellerId=USR2021072300001&channelSeqId=SPO20231031000001
    this.callback_url = location.href.split('#/?callbackUrl=')[1]
    if (!this.callback_url) {
      this.callback_url = ''
    } else {
      console.log(this.callback_url)
    }
  }
}
</script>

<style>

.heading {
  text-align: center;
  margin-bottom: 48px;
}
.heading h1 {
  color: #333;
  line-height: 1.15;
  font-size: 64px;
  margin-bottom: 32px;
}
.heading h1 span {
  position: relative;
}
.heading h1 span::after {
  content: "";
  position: absolute;
  z-index: -1;
  left: 0;
  bottom: 8px;
  width: 100%;
  height: 20px;
  background: #ecf6ff;
}
.heading p {
  font-size: 32px;
  color: #666;
  line-height: 56px;
}
.md-example-child-agree .md-agree-content {
  color: #858b9c;font-size:18px;
}
.md-example-child-agree {
  margin-top: 70px;
  padding: 0 32px;
  font-size: 12px;
}
.md-example-popup {
  position:relative;
  font-size:28px;
  font-family:DINPro;
  font-weight:500; box-sizing:border-box;
  text-align: center;
  background-color: #FFF;
}
.md-example-popup-center {
  padding: 50px;
  border-radius: radius-normal;
}
.md-example-popup-bottom {
  width: 100%;
  height: 500px;
  padding: 20px 0;
}
.choose_left_1{
  float:left;padding-left: 80px;
}
.choose_right_1{
  float:left;padding-left: 80px;
}
.choose_center_1{
  padding-left: 10px;
  padding-right: 10px;
  padding-top: 10px;
  padding-bottom: 10px;
  text-align: center;
}
.choose_next_1{
  height:80px;
  text-align: center;
  width:300px;
  font-size: 18px;
  padding-left: 20px;
  padding-left: 10px;
  margin: 0 auto;
}
</style>
